package Service;

import DAL.SqlHelper;
import Entity.News;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NewsService {
    public boolean AddNews(News news){
        String sql="INSERT INTO news ( category, title,content,author, newsdate)" +
                " VALUES( '"+news.getCategory()+"', '"+news.getTitle()+"','"+news.getContent()+"', " +
                "'"+news.getAuthor()+"','"+String.valueOf(news.getNewsdate())+"');";
        return SqlHelper.executeUpdate(sql);
    }

    public boolean DeleteNews(int idnews){
        String sql ="delete from news where idnews="+Integer.toString(idnews);
        System.out.println(sql);
        boolean rs=SqlHelper.executeUpdate(sql);
        return  rs;
    }

    public boolean UpdateNews(News news) {
        String sql ="update news set category='"+news.getCategory()+"',title='"+news.getTitle()
                +"',content='"+news.getContent()+"',author='"+news.getAuthor()+"'," +
                "newsdate='"+String.valueOf(news.getNewsdate())+"' where idnews="+news.getIdnews()+"";
         return  SqlHelper.executeUpdate(sql);
    }

    public List<News> QueryNews() throws SQLException {
        String sql="Select * from news";
        ResultSet rs= SqlHelper.executeQuery(sql);
        List<News> lsNews=new ArrayList<News>();
        while (rs.next())
        {
            News news=new News();
            news.setIdnews(rs.getInt(1));
            news.setCategory(rs.getString(2));
            news.setTitle(rs.getString(3));
            news.setContent(rs.getString(4));
            news.setAuthor(rs.getString(5));
            news.setNewsdate(rs.getDate(6));
            lsNews.add(news);
        }
        return lsNews;
    }

    public News GetNews(int idnews) throws SQLException {
        String sql="Select * from news where idnews='"+Integer.toString(idnews)+"'";
        ResultSet rs= SqlHelper.executeQuery(sql);
        if (rs.next())
        {
            News news=new News();
            news.setIdnews(rs.getInt(1));
            news.setCategory(rs.getString(2));
            news.setTitle(rs.getString(3));
            news.setContent(rs.getString(4));
            news.setAuthor(rs.getString(5));
            news.setNewsdate(rs.getDate(6));
            return news;
        }
        return null;
    }
}
